package com.zn.controller;

import com.alibaba.fastjson.JSON;
import com.zn.pojo.User;
import com.zn.service.UserService;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
public class UserController {

    @Autowired
    UserService us;

    //添加用户
    @RequestMapping("/add")
    public String addUser(User user,String id)  {

        try {
            us.addPlayer(user, id);
            return "true";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "false";
    }

    //查询该用户
    @RequestMapping("/getPlayer/{id}")
    public String getPlayer(@PathVariable("id") String id) throws IOException {

        Map<String, Object> map = us.getPlayer(id);

        if (map==null){
            return "没该用户";
        }

        String s = JSON.toJSONString(map);

        return s;
    }

    //批量插入数据
    @RequestMapping("/bluckAdd")
    public String bluckAdd() throws IOException {

        try {
            int i = us.bluckUser();
            return "成功插入了"+i+"条数据";
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "插入过程有误";
    }

    //修改es中的用户
    @RequestMapping("/updateUser")
    public String updateUser(User user,String id){
        Boolean flag = us.updateUser(user, id);
        if (flag){
            return "---该用户修改成功---";
        }
        return "---没有查询到该用户---";
    }

    //删除es中的用户
    @RequestMapping("/delete/{id}")
    public String deleteUser(@PathVariable("id") String id) throws IOException {
        Boolean flag = us.deleteUser(id);
        if (flag){
            return "用户删除成功";
        }
        return "没有查询到该用户";
    }

    //单条件匹配查询+分页查询
    @RequestMapping("/search/{key}/{val}")
    public List<User> limitUser(@PathVariable("key") String key,@PathVariable("val")String val) throws IOException {
        List<User> userList = us.searchMach(key, val);
        return userList;
    }

    //词条查询
    @RequestMapping("/search1/{key}/{val}")
    public List<User> limitUser2(@PathVariable("key") String key,@PathVariable("val")String val) throws IOException {
        List<User> userList = us.searchTerm(key, val);
        return userList;
    }

    //前缀匹配查询
    @RequestMapping("/search2/{key}/{val}")
    public List<User> limitUser3(@PathVariable("key") String key,@PathVariable("val")String val)throws IOException{
        List<User> userList = us.searchMatchPrefix(key, val);
        return userList;
    }

    //多条件查询
    @RequestMapping("/search3")
    public List<User> limitUser3()throws IOException{
        List<User> userList = us.searchMore();
        return userList;
    }

}
